import React, { useState, useEffect } from 'react'
import axios from 'axios'

export default function () {
    const [data, setData] = useState('')
    const [query, setQuery] = useState('')
    const [url, setUrl] = useState('http://wthrcdn.etouch.cn/weather_mini?city=青岛')
    const [isLoading, setIsLoading] = useState(false)
    const [isError, setIsError] = useState(false)

    useEffect(() => {
        const fetchData = async () => {
            setIsLoading(true)
            setIsError(false)
            try{
                const ret = await axios(url)
                setData(ret.data.data)
            }catch(e){
                setIsError(true)
            }
            setIsLoading(false)
        }
        fetchData()
    }, [url])

    return (
        <div>
            <h2>loading+错误捕捉+表单提交</h2>
            <p>输入内容后可直接按回车</p>
            <form onSubmit={(e) =>{e.preventDefault(); setUrl('http://wthrcdn.etouch.cn/weather_mini?city=' + query)}}>
                <input value={query} onChange={e => setQuery(e.target.value)} />
                <button type='submit'>搜索</button>
            </form>

            {isError&&<div style={{background:'pink',padding:'1rem',margin:'1rem'}}>出错啦~~</div>}

            {data && (isLoading
                ? <div> loading...</div>
                : <>
                    <p><strong>城市：</strong>{data.city}</p>
                    <p><strong>当前温度：</strong>{data.wendu}℃</p>
                    <p><strong>感冒预警：</strong>{data.ganmao}</p>
                    <h4>未来{data.forecast?.length}天天气情况</h4>
                    <ul>
                        {data.forecast?.length
                            ? data.forecast.map(item => <li key={item.date}>{`${item.date} - ${item.type} - ${item.low}~${item.high}`}</li>)
                            : null}
                    </ul>
                </>)}

        </div>
    )
}
